package com.guinea.core.web;

import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.guinea.core.orm.Page;
import com.guinea.core.orm.PropertyFilter;
import com.guinea.core.utils.ServletUtils;

/**
 * 负责管理单个Entity CRUD操作的Struts Action基类. <p/> 子类以以下方式声明,并实现将拥有默认的CRUD函数 <p/>
 * 
 * <pre>
 *              public class UserAction extends StrutsEntityAction&lt;User, UserDao&gt; {
 *              	private UserDao userDao;
 *            &lt;p/&gt;
 *              	public void setUserDao(UserDao userDao) {
 *              		this.userDao = userDao;
 *              	}
 *              }
 * </pre>
 * 
 * <p/> 此类仅演示一种封装的方式，大家可按自己的项目习惯进行重新封装 <p/> 目前封装了：<br/>
 * 1.index、list、create、edit、view、save、delete 七种action的流程封装；<br/>
 * 2.doListEntity、doGetEntity、doNewEntity、doSaveEntity(),doDeleteEntity
 * 五种业务函数调用，可在子类重载；<br/>
 * 3.initEntity、initForm两个FormBean与业务对象的初始函数及refrenceData,onInitForm,
 * onInitEntity 三个回调函数；<br/> 4.savedMessage、deletedMessage 两种业务成功信息，可在子类重载。<br/>
 * 
 * @author calvin
 */
public abstract class StrutsEntityAction extends StrutsSimpleAction {
	protected Logger logger = LoggerFactory.getLogger(getClass());

	public static final String LIST = "list";

	public static final String EDIT = "edit";

	public static final String VIEW = "view";

	/**
	 * url参数未定义method时的默认Action函数. 默认为index Action.
	 */
	public ActionForward unspecified(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) {
		return list(mapping, form, request, response);
	}

	/**
	 * 列出所有对象的Action函数.
	 */
	public ActionForward list(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) {
		// 从request中获取含属性前缀名的参数,构造去除前缀名后的参数Map.
		Map filterParamMap = ServletUtils.getParametersStartingWith(request,
				FILTER_PREFIX + "_");
		List filters = PropertyFilter.buildFromParaMap(filterParamMap);
		Page page = PropertyFilter.buildPageFromHttpRequest(request,
				REQUEST_PAGE);

		page = getEntityService().findPage(page, filters);

		request.setAttribute(REQUEST_PAGE, page);
		request.setAttribute(FILTER_MAP, filterParamMap);
		return mapping.findForward(LIST);
	}
	
	/**
	 * edit验证.
	 */
	public ActionForward editValidator(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) {
		initFirst(form,request);
		return null;
	}
	
	/**
	 * 显示修改对象Form的Action函数.
	 */
	public ActionForward edit(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) {

		bindForm(form, entity);

		return handleEdit(mapping,form,request,response);
	}
	
	/**
	 * 保存前的验证.
	 */
	public ActionForward saveValidator(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) {
		if(isCancelled(request)){
			valid = false;
			return mapping.findForward(LIST);
		}
			
		if (!validateToken(request))
			return handleToken(mapping,form,request,response);
		
		initFirst(form,request);
		if(!validateForm(mapping,form,request))
			return handleFormErrors(mapping,form,request,response);
		return null;
	}
	
	/**
	 * 保存对象的Action函数.
	 */
	public ActionForward save(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) {

		doInitEntity(request,form);
		
		doSaveEntity(request,form);

		saveMessage(request, "entity.saved");
		return mapping.findForward(SUCCESS);
	}
	
	/**
	 * view验证.
	 */
	public ActionForward viewValidator(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) {
		initFirst(form,request);
		if(!validateEntity())
			return handleEntityMissing(mapping,form,request,response);
		return null;
	}
	
	/**
	 * 查看业务对象（不能修改）的Action函数.
	 */
	public ActionForward view(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) {

		request.setAttribute(REQUEST_ENTITY, entity);

		return mapping.findForward(VIEW);
	}
	
	/**
	 * erase验证.
	 */
	public ActionForward eraseValidator(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) {
		initFirst(form,request);
		if(!validateEntity())
			return handleEntityMissing(mapping,form,request,response);
		return null;
	}
	
	/**
	 * 标记删除单个对象的Action函数.
	 */
	public ActionForward erase(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) {

		doEraseEntity(request);

		saveMessage(request, "entity.deleted");
		return mapping.findForward(SUCCESS);
	}
	

	protected ActionForward handleEntityMissing(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) {
		saveError(request, "entity.missing");
		return mapping.findForward(LIST);
	}

	protected ActionForward handleToken(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) {
		saveError(request, "submit.duplicated");
		return handleEdit(mapping,form,request,response);
	}

	protected ActionForward handleFormErrors(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) {
		saveErrors(request, formErrors);
		return handleEdit(mapping,form,request,response);
	}

	protected ActionForward handleEdit(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response){
		saveToken(request);
		return mapping.findForward(EDIT);
	}

}
